package tw.com.diary.dao;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class BaseDAO<ID, DOMAIN> {

	final String x0001 = "x0001";

	final SQLiteDatabase conn;

	BaseDAO(SQLiteDatabase conn) {
		this.conn = conn;
	}

	public SQLiteDatabase getConn() {
		return conn;
	}

	public List<DOMAIN> formCursor(Cursor c) {
		final List<DOMAIN> tmps = new ArrayList<DOMAIN>();
		final String[] colums = this.getCoulumns();

		if (c.getCount() == 0) {
			return tmps;
		}

		c.moveToFirst();
		try {

			for (int i = 0; i < c.getCount(); i++) {
				DOMAIN domain = getMyClass().newInstance();
				for (String column : colums) {

					this.setValue(column, domain,
							c.getString(c.getColumnIndex(column)));

				}
				tmps.add(domain);
				c.moveToNext();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return tmps;
	}

	public abstract String[] getCoulumns();

	public abstract Class<DOMAIN> getMyClass();

	private void setValue(String name, DOMAIN domain, Object value) {
		try {
			final Field field = domain.getClass().getDeclaredField(name);
			field.setAccessible(true);
			field.set(domain, value);
			field.setAccessible(false);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
